package org.ohos.rajawali3d.examples;


import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;
import opengl.platform.ohos.Log;
import org.ohos.rajawali3d.ResourceTable;
import org.ohos.rajawali3d.examples.utils.PermissionHelper;

public class LauncherAbility extends FractionAbility {

    private static final String TAG = "LauncherActivity";

    private static final int REQUEST_PERMISSIONS = 1;


    @Override
    public void onStart(Intent savedInstanceState) {
        super.onStart(savedInstanceState);
        super.setUIContent(ResourceTable.Layout_activity_launcher);
        //super.setMainRoute(MainAbilitySlice.class.getName());
        getFractionManager().startFractionScheduler().replace(ResourceTable.Id_content_frame, new ExamplesFragment(getContext()))
                .submit();
        PermissionHelper.init(getContext());
        PermissionHelper.getInstance().requestPermissions();
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode,
                                                   String[] permissions,
                                                   int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSIONS:
                if (hasAllPermissions(permissions)) {
                    Log.d(TAG, "All permissions granted!");
                } else {
                    (new ToastDialog(this))
                            .setText("Cannot continue running Rajawali Examples without all required permissions.")
                            .setDuration(10000)
                            .show();
                    terminateAbility();
                }
                break;
            default:
                super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        }
    }
/* TODO: context menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_settings:
                startActivity(new Intent(this, WallpaperPreferenceActivity.class));
                return true;
        }

        return super.onOptionsItemSelected(item);
    }
*/

    /**
     * Determine if the application has the necessary permissions to perform an action.
     *
     * @param permissions permissions to check
     * @return true if application has all permissions
     */
    boolean hasAllPermissions(String[] permissions) {
        for (String permission : permissions) {
            final int result = verifySelfPermission(permission);
            if (result != IBundleManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
}
